package com.guigu.dealservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.dealservice.dto.Equipment;
import com.guigu.dealservice.entity.EquipmentReservation;
import com.guigu.dealservice.entity.MonthlyData;
import com.guigu.dealservice.entity.Order;
import com.guigu.dealservice.feign.MyEquipmentFeign;
import com.guigu.dealservice.service.EquipmentReservationService;
import com.guigu.dealservice.service.OrderService;
import com.guigu.dealservice.vo.OrderVo;
import com.guigu.equipmentservice.service.EquipmentService;
import com.guigu.dealservice.vo.PageOrderVoPC;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 订单表（存储买卖双方的交易订单信息） 前端控制器
 * </p>
 *
 * @author ysp
 * @since 2025-10-10
 */
@RestController
@RequestMapping("/dealservice/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private MyEquipmentFeign myEquipmentFeign;

    @Autowired
    private EquipmentReservationService equipmentReservationService;

    /**
     * 前台--根据用户id查询订单
     * @param userId
     * @return
     */
    @GetMapping("/queryOrderByUserId/{userId}")
    public R queryOrderByUserId(@PathVariable Long userId) {
        return R.ok().data("items", orderService.queryOrderByUserId(userId));
    }

    /**
     * 前台--根据设备id查询订单
     *
     *@return
     */
    @GetMapping("/queryOrderByEquipmentId/{equipmentId}")
    public R queryOrderByEquipmentId(@PathVariable("equipmentId") Long equipmentId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_id", equipmentId);


        List<Order> list = orderService.list(wrapper);

        int val=0;
        if (list!=null){
            for (Order order:list){
                if (order.getOrderStatus()!=7){
                    val++;
                }
            }
        }else{
            return R.ok().code(20000).message("ok").data("success", true);
        }

        if (val==0)
            return R.ok().code(20000).message("ok").data("success", true);
        return R.error().code(20001).message("该设备已预定").data("success", false);
    }

    /**
     * 前台--根据设备id查询订单
     *
     *@return
     */
    @GetMapping("/queryOrderByEquipmentId2/{equipmentId}")
    public R queryOrderByEquipmentId2(@PathVariable("equipmentId") Long equipmentId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_id", equipmentId);
        wrapper.ne("order_status", 7);
        Order items = orderService.getOne(wrapper);

         return R.ok().data("items",items);
    }


    /**
     * 前台--根据设备id查询订单
     *
     *@return
     */
    @GetMapping("/queryOrderByEquipmentId3/{equipmentId}")
    public Order queryOrderByEquipmentId3(@PathVariable("equipmentId") Long equipmentId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_id", equipmentId);
        return orderService.getOne(wrapper);
    }

    /**
     * 前台-根据买家的id和已完成的状态去查询该买家购买的全部订单设备信息
     *
     * @param
     * @return
     */
    @GetMapping("/selectOrderBybuyerIdAndorderStatus/{id}/{pageNum}/{pageSize}")
    public R selectOrderBybuyerIdAndorderStatus(@PathVariable("id") Long id, @PathVariable("pageNum") Integer pageNum,
                                                @PathVariable("pageSize") Integer pageSize) {

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("buyer_id", id);


        List<Order> list = orderService.list(orderQueryWrapper);

        for (Order order : list) {
            //远程调用-查询设备的信息
            Equipment equipment = myEquipmentFeign.queryEquipmentAndImageAndType2(order.getEquipmentId());
            order.setEquipmentdx(equipment);
        }

        int total = list.size();
        int startIndex = (pageNum - 1) * pageSize;

        // 边界检查：确保 startIndex 不超过总数据量
        if (startIndex >= total) {
            // 如果起始索引超出范围，返回空列表
            return R.ok()
                    .data("list", new ArrayList<>())
                    .data("total", total);
        }

        int endIndex = Math.min(startIndex + pageSize, total);
        List<Order> orders = list.subList(startIndex, endIndex);

        return R.ok()
                .data("orders", orders)
                .data("total", total);
    }

    /**
     * 前台个人中心-查询全部订单信息
     *
     * @param
     * @return
     */
    @PostMapping("/selectAllOrderInfo/{pageNum}/{pageSize}")
    public R selectAllOrderInfo(@PathVariable("pageNum") Integer pageNum,
                                @PathVariable("pageSize") Integer pageSize, @RequestBody PageOrderVoPC vo) {
        List<Order> list;
        if (vo != null) {
            if (vo.getOrderStatus() == null) {
                QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(vo.getStartTime()))
                    orderQueryWrapper.ge("create_time", vo.getStartTime());
                if (!StringUtils.isEmpty(vo.getEndTime()))
                    orderQueryWrapper.le("create_time", vo.getEndTime());
                // 用户角色条件 - 关键修正
                if (vo.getBuyerId() != null && vo.getSellerId() != null) {
                    // 既是买家又是卖家
                    orderQueryWrapper.and(wrapper ->
                            wrapper.eq("buyer_id", vo.getBuyerId())
                                    .or()
                                    .eq("seller_id", vo.getSellerId())
                    );
                }
                list = orderService.list(orderQueryWrapper);
            } else {
                QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(vo.getStartTime()))
                    orderQueryWrapper.ge("create_time", vo.getStartTime());
                if (!StringUtils.isEmpty(vo.getEndTime()))
                    orderQueryWrapper.le("create_time", vo.getEndTime());
                // 用户角色条件 - 关键修正
                if (vo.getBuyerId() != null && vo.getSellerId() != null) {
                    // 既是买家又是卖家：使用 OR 查询
                    orderQueryWrapper.and(wrapper ->
                            wrapper.eq("buyer_id", vo.getBuyerId())
                                    .or()
                                    .eq("seller_id", vo.getSellerId())
                    );
                }
                if (vo.getOrderStatus() != null) {
                    if (vo.getOrderStatus() == 1) {
                        orderQueryWrapper.in("order_status", 1);
                    }else{
                        orderQueryWrapper.eq("order_status", vo.getOrderStatus());
                    }
                }

                list = orderService.list(orderQueryWrapper);
            }
        }else {
            // vo为null，查询所有订单
            list = orderService.list();
        }

        for (Order order : list) {
            // 远程调用-查询设备的信息
            Equipment equipment = myEquipmentFeign.queryEquipmentAndImageAndType2(order.getEquipmentId());
            order.setEquipmentdx(equipment);
        }

        int total = list.size();
        int startIndex = (pageNum - 1) * pageSize;

        // 边界检查：确保 startIndex 不超过总数据量
        if (startIndex >= total) {
            // 如果起始索引超出范围，返回空列表
            return R.ok()
                    .data("orders", new ArrayList<>())
                    .data("total", total);
        }

        int endIndex = Math.min(startIndex + pageSize, total);
        List<Order> orders = list.subList(startIndex, endIndex);

        return R.ok()
                .data("orders", orders)
                .data("total", total);
    }


    /**
     * 前台个人中心-取消未支付定金的订单
     *
     * @param
     * @return
     */
    @PutMapping("/editOrderstatusByoId/{id}")
    public  R editOrderstatusByoId(@PathVariable("id") Integer id){

        Order byId = orderService.getById(id);

        byId.setOrderStatus(7);

        boolean b = orderService.updateById(byId);

        if (b==true)
               return R.ok().code(20000).message("取消成功").data("success", true);
            return R.error().code(20001).message("取消失败").data("success", false);
    }

    /**
     * 前台个人中心-确认收货后修改订单状态和设备的用户
     *
     * @param
     * @return
     */
    @PutMapping("/editOrderAndEquipmentUserId/{id}")
    public  R editOrderAndEquipmentUserId(@PathVariable("id") Integer id){

        Order byId = orderService.getById(id);

        byId.setOrderStatus(5);

        boolean b = orderService.updateById(byId);

        if (b==true)
            return R.ok().code(20000).message("已收货").data("success", true);
        return R.error().code(20001).message("收货失败").data("success", false);
    }

    /**
     * 后台-查询订单列表
     * @param pageNum
     * @param pageSize
     * @param vo
     * @return
     */
    @PostMapping("/queryOrderListByVo/{pageNum}/{pageSize}")
    public R queryOrderListByVo(@PathVariable Integer pageNum,
                                @PathVariable Integer pageSize,
                                @RequestBody OrderVo vo) {
        return orderService.queryOrderListByVo(pageNum, pageSize, vo);
    }
    /**
     * 后台-查询订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/queryOrderById/{orderId}")
    public R queryOrderById(@PathVariable Long orderId) {
        return orderService.queryOrderById(orderId);
    }

    /**
     * 前台个人中心-卖家点击发货按钮
     *
     * @param
     * @return
     */
    @PutMapping("/editOrderStatusSi/{id}")
    public  R editOrderStatusSi(@PathVariable("id") Integer id) {

        Order byId = orderService.getById(id);

        byId.setOrderStatus(4);

        boolean b = orderService.updateById(byId);

        if (b==true)
            return R.ok().code(20000).message("已发货").data("success", true);
        return R.error().code(20001).message("发货失败").data("success", false);
    }


    @GetMapping("/queryUserById/{uid}")
    public R queryUserById(@PathVariable("uid") Integer uid) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("buyer_id", uid)
                .or()  // 关键：添加 or() 表示“或者”关系
                .eq("seller_id", uid);
        List<Order> list = orderService.list(orderQueryWrapper);
        return R.ok().data("list", list);
    }

    @GetMapping("/recent-six-months")
    public R getRecentSixMonthsData() {
        List<MonthlyData> data = orderService.getRecentSixMonthsData();
        List<String> month=new ArrayList<>();
        List<Integer> volume=new ArrayList<>();
        List<BigDecimal> amount=new ArrayList<>();
        for (MonthlyData m :data) {
            month.add(m.getMonth());
            volume.add(m.getVolume());
            amount.add(m.getAmount());
        }
        return R.ok().data("month", month).data("volume", volume).data("amount", amount);
    }

    /**
     * 前台个人中心-修改订单状态6
     *
     * @param
     * @return
     */
    @PutMapping("/editOrderStatusLiu/{id}")
    public  R editOrderStatusLiu(@PathVariable("id") Integer id){

        Order byId = orderService.getById(id);

        byId.setOrderStatus(6);

        boolean b = orderService.updateById(byId);

        //在修改设备是已成交
        String s = myEquipmentFeign.editequipmentStatusChengJiao(byId.getEquipmentId());

        if (s.equals("ok"))
            return R.ok().code(20000).message("已完全").data("success", true);
        return R.error().code(20001).message("修改失败").data("success", false);
    }

    //根据订单的检测状态去查询订单数据
    @GetMapping("/queryAllOrderByInspectionStatusOne/{id}")
    public  List<Order>  queryAllOrderByInspectionStatusOne(@PathVariable("id") Integer id){

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("inspection_status",1);
        List<Order> list = orderService.list(orderQueryWrapper);

        return list;
    }
    @GetMapping("/getOrderByEqIdAndInspection/{Eid}")
    public Order getOrderByEqIdAndInspection(@PathVariable("Eid") Long Eid,@RequestParam(value = "inspection", required = false) Integer inspection){
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Eid!=null){
            orderLambdaQueryWrapper.eq(Order::getEquipmentId,Eid);
        }
        if (inspection !=null){
            orderLambdaQueryWrapper.eq(Order::getInspectionStatus,inspection);
        }
        Order order = orderService.getOne(orderLambdaQueryWrapper);
        if (order==null)
            return null;
        return order;
    }


    @PutMapping("/update1/{id}")
    public Boolean update1(@PathVariable("id") Integer eid) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("equipment_id", eid);
        orderQueryWrapper.eq("inspection_status", 1);
        Order one = orderService.getOne(orderQueryWrapper);
        one.setInspectionStatus(2);
        boolean update = orderService.updateById(one);
        return update;
    }


    //修改支付按钮状态
    @PutMapping("/editOrderStatusPay/{id}")
    public  R editOrderStatusPay(@PathVariable("id") Integer id){
        Order byId = orderService.getById(id);
        byId.setOrderStatus(3);
        boolean b = orderService.updateById(byId);
        if (b==true){
            return R.ok().code(20000).message("已支付").data("success", true);
        }else{
            return R.error().code(20001).message("支付失败").data("success", false);
        }
        }
}
